package spark

import (
	"context"
	"fmt"
	"github.com/iflytek/spark-ai-go/sparkai/llms/spark"
	"github.com/iflytek/spark-ai-go/sparkai/llms/spark/client/sparkclient"
	"github.com/iflytek/spark-ai-go/sparkai/messages"
	"roc/wechat/global"
	"strings"
)

type Spark struct {
}

var client *sparkclient.Client

func InitSpark() {
	if global.CONFIG.Spark.AiUrl == `` {
		panic("讯飞星火url未配置")
	}
	_, cli, err := spark.NewClient(spark.WithBaseURL(global.CONFIG.Spark.AiUrl), spark.WithApiKey(global.CONFIG.Spark.AiApiKey), spark.WithApiSecret(global.CONFIG.Spark.AiApiSecret), spark.WithAppId(global.CONFIG.Spark.AiAppId), spark.WithAPIDomain(global.CONFIG.Spark.AiDomain))
	if err != nil {
		fmt.Println("讯飞星火大模型 连接失败，err:", err)
		return
	}

	client = cli

	global.AiClient = Spark{}
}

// GetDefaultInfo
// @Description: 获取默认的信息
// @return defaultMessageList
func (m Spark) GetDefaultInfo() (defaultMessageList interface{}) {
	return []messages.ChatMessage{
		&messages.GenericChatMessage{
			Role:    "system",
			Content: "你现在是微信小助手，你豪情万丈，狂放不羁；接下来请用李白的口吻和用户对话。",
		},
	}
}

func (m Spark) Chat(msg string, historyMessageList interface{}) (content string, newMessageList interface{}, err error) {
	messageList := historyMessageList.([]messages.ChatMessage)
	messageList = append(messageList, &messages.GenericChatMessage{
		Role:    "user",
		Content: msg,
	})
	ctx := context.Background()
	r := &sparkclient.ChatRequest{
		Domain:   &global.CONFIG.Spark.AiDomain,
		Messages: messageList,
	}

	respMessageList := make([]string, 0)
	_, err = client.CreateChatWithCallBack(ctx, r, func(msg messages.ChatMessage) error {
		fmt.Print(msg.GetContent())
		respMessageList = append(respMessageList, msg.GetContent())
		return nil
	})
	if err != nil {
		fmt.Print(err.Error())
		return
	}

	content = strings.Join(respMessageList, "")

	messageList = append(messageList, &messages.GenericChatMessage{
		Role:    "assistant",
		Content: content,
	})
	newMessageList = messageList

	return
}
